<template>
    <input class="fileupload" id="{{id}}" name="{{name}}" type="file" multiple="{{multiple}}"
    accept="image/*" capture="camera">
    <modal :data-id = "id+'uploadModal'" :data-show="status" :data-type="'confirm'" :data-title="'upload'"  :data-close-btn="{'text':'取消'}" :data-confirm-btn="{'text':'上传'}" v-ref:modal-upload-file>
        <div slot="msg"
    		 class="progress progress-striped active" 
        	 role="progressbar" 
        	 aria-valuemin="0" 
        	 aria-valuemax="100">
            <div class="progress-bar progress-bar-success" style="width:0%;"></div>
        </div>
    </modal>
</template>

<style lang="sass" scoped>
	.fileupload {
	    position: absolute;
	    top: 0;
	    left: 0;
	    right: 0;
	    margin: 0;
	    opacity: 0;
	    -ms-filter: 'alpha(opacity=0)';
	    /* font-size: 200px !important; */
	    /* direction: ltr; */
	    cursor: pointer;
	    display: block;
	    width: 100%;
		height: 100%;
		}
</style>

<script>
require('../../public/plugins/jquery-file-upload/js/vendor/jquery.ui.widget.js');
//require('../../public/plugins/jquery-file-upload/js/jquery.iframe-transport.js');
require('../../public/plugins/jquery-file-upload/js/jquery.fileupload-image.js');
export default {

	replace: true,
	props: {
		id       : '',
		name     : '',
		url      : '',
		disableImageResize :{           //值为false时会压缩图片上传
			type: Boolean,
			default: false
		},
		formData : new Object,
		autoUpload : {           //值为false时会有弹窗
			type: Boolean,
			default: false
		},         
		multiple :  {
			type: Boolean,
			default: false
		}
	},
	components: {
		'modal': require("./modal.vue")
	},
	data() {

		return {

			files: new Array,
			fileData: '',
			formDatas: this.formData,
			status: false       //show modal
		}
	},
	methods: {

		/**
		 * 上传
		 * @function
		 * @name upload
		 * @return 返回值为数字类型
		 */
		init() {

			let self = this;

			let	id       	= self.$get('id'),
				url      	= self.$get('url'),
				autoUpload 	= self.$get('autoUpload'),
				formData 	= self.$get('formDatas');
			if (!url)  return false;
			$('#'+id).fileupload({
		        url: url,
		        type:"POST",
		        autoUpload : autoUpload,
		        dataType: 'json',
		        maxFileSize:10000000, // 10 MB
		        formData: formData,
		        //图片压缩配置 默认启用压缩
		        disableImageResize:false,
		        imageMaxWidth: 800,
			    imageCrop: false, // Force cropped images
			    //change add to processalways 等待所有异步任务跑完再设置上传
		        processalways: function(e,data){

					if(!autoUpload){

						self.$refs.modalUploadFile.shows();
						self.$set("fileData",data);

					}else{
						self.upload(data);
					}

		        	 self._add(data);
		        	
		        },
		        done: function (e, data) {

		        	// done方法就是上传完毕的回调函数，其他回调函数可以自行查看api
			        // 注意result要和jquery的ajax的data参数区分，这个对象包含了整个请求信息
			        // 返回的数据在data.result中，假设我们服务器返回了一个json对象
		        	let files = [];

		        	
		        	files.push(data.result.list);

		            /*$.each(data.result.list, function (index, file) {

		            	files.push(file);
		            });*/
					

		            if(!autoUpload){

			        	 setTimeout(function(){
			        	 	
							self.$refs.modalUploadFile.hides();     //hide modal

			        	 },600);
		            	
		            }

		            self._done(files);

		        },
		        progressall: function (e, data) {

		        	// 换算成百分数，并作为参数传入进度回调方法
		            var percent = parseInt(data.loaded / data.total * 100, 10) + '%';

		            $('.progress .progress-bar').css(
			            'width',
			            percent
			        );

		            self._progress(percent);
		        },
		        fail: function(e,data){
		        	console.log("fail");
		        }
		    });
		},
		/**
		 * 设置上传参数
		 * @param {Object} val [description]
		 */
		setFormData(valObj){
			this.destroy();
			this.formDatas = valObj;
			this.init();
			
		},

		/**
		 * 启用组件
		 * @function
		 * @name destroy
		 */
		enable() {

			let id = '#' + this.$get('id');

			$(id).fileupload('enable');
		},

		/**
		 * 禁用组件
		 * @function
		 * @name destroy
		 */
		disable() {

			let id = '#' + this.$get('id');

			$(id).fileupload('disable');
		},

		/**
		 * 销毁组件
		 * @function
		 * @name destroy
		 */
		destroy() {

			let id = '#' + this.$get('id');

			$(id).fileupload('destroy');
		},

		/**
		 * 增加文件完成回调方法
		 * @param {[type]} data [description]
		 */
		_add(data) {

			
		},
		/**
		 * 取消上传
		 * @param  {Object} data [description]
		 * @return {[type]}      [description]
		 */
		cancelUplod(data){

			data.abort();
		},

		/**
		 * 上传文件
		 * @param  {[type]} data [description]
		 * @return {[type]}      [description]
		 */
		upload(data) {

			data.submit();

			//this.disable();
		},

		/**
		 * 上传完成
		 * @function
		 * @private
		 * @name done
		 * @param {array} files 文件列表
		 */
		_done(files) {

			this.doneCall(files);
		},

		/**
		 * 上传完成回调方法
		 * @function
		 * @name done
		 * @param {array} files 文件列表
		 * @example:
		 * xx.$refs.upload.doneCall(files) { console.log(files) }
		 */
		doneCall(files) {},

		/**
		 * 上传进度
		 * @function
		 * @private
		 * @name progress
		 * @param {string} percent 百分数
		 */
		_progress(percent) {

			this.progressCall(percent);
		},

		/**
		 * 上传进度回调方法
		 * @function
		 * @name progress
		 * @param {string} percent 百分数
		 * @example:
		 * xx.$refs.upload.progressCall(percent) { console.log(percent) }
		 */
		progressCall(percent) {}
	},
	ready() {

		let self = this;

		self.init();

		self.$refs.modalUploadFile.confirm = function(){

			let uploadBtn = $("#userInfouploadModal").find(".btn-primary")[0];

			uploadBtn.setAttribute("disabled",true);

			let data = self.$get("fileData");

			self.upload(data);
		}
		self.$refs.modalUploadFile.hidden = function(){

			let data = self.$get("fileData"),
				uploadBtn = $("#userInfouploadModal").find(".btn-primary")[0];

			self.cancelUplod(data);

			$('.progress .progress-bar').css(        //清空progress 
	            'width',
	            '0%'
	        );
			
			uploadBtn.removeAttribute("disabled");
			
		}
	}
}
</script>